package com.dwin.h5.app.ui;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dwin.h5.app.R;
import com.dwin.h5.app.models.TabItem;
import com.dwin.h5.app.models.response.HomeTabRsp;
import com.dwin.h5.app.ui.system.LoginActivity;
import com.dwin.h5.app.utils.ActivityUtils;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.LocalManageUtil;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.utils.http.UserManageRetrofit;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * 启动页面
 */
public class LoadingActivity extends BaseActivity {
    private static final String TAG = "LoadingActivity";
    private TextView mCountDownTextView;
    private MyCountDownTimer mCountDownTimer;
    private boolean isFirstTime; // 是否第一次使用本app

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        setTheme(R.style.Splash_Theme);
        mContext = this;

        mCountDownTextView = findViewById(R.id.start_skip_count_down);
        mCountDownTextView.setText("3s 跳过"); //创建倒计时类
        mCountDownTimer = new MyCountDownTimer(2900, 1000);
        mCountDownTimer.start(); //这是一个 Handler 里面的逻辑是从 Splash 界面跳转到 Main 界面，这里的逻辑每个公司基本上一致

        // 倒计时点击，跳转到首页面
        findViewById(R.id.start_skip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCountDownTimer != null) { // 修改倒计时剩余1s左右，点击跳转，会存在2个登录页面的问题。
                    mCountDownTimer.cancel();
                    mCountDownTimer = null;
                }
                Log.d(TAG, "jumpToHomePage: start_skip");
                jumpToHomePage();
            }
        });

        isFirstTime = logMessage.getBoolean("runAppFirstTime", true);
        if (isFirstTime) { // 首次运行app
            // getTabsInfo();
            logMessage.edit().putBoolean("runAppFirstTime", false).commit();
        } else { // 非首次运行app
            // jumpToHomePage();
        }
        getTabsInfo();
    }

    // 获取主页面，tab的信息，登录H5页面的url信息
    // TODO 获取app通用信息，要添加language字段到header中，用于获取国际化tab标题资源
    private void getTabsInfo() {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        String language = LocalManageUtil.getSystemLocaleLng(mContext);
        UserManageRetrofit.getInstance().getHomeTabs(language, new retrofit2.Callback<HomeTabRsp>() {
            @Override
            public void onResponse(retrofit2.Call<HomeTabRsp> call, Response<HomeTabRsp> response) {
                if (Constants.HTTP_OK == response.body().code) {
                    logMessage.edit().putString("loginUrl", response.body().data.login_url).commit();
                    logMessage.edit().putString("version", response.body().data.version).commit();
                    Log.d(TAG, "onResponse: " + response.body().data.tabs.toString());
                    ArrayList<TabItem> tabs = response.body().data.tabs;
                    LitePal.deleteAll(TabItem.class); // clear saved data
                    for (int i = 0; i < tabs.size(); i++) {
                        tabs.get(i).save();
                    }
                    findAllData();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<HomeTabRsp> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }

    private void jumpToHomePage() {
        // 已登录用户，进入首页面；未登录用户，进入登录页面
        if (mUser != null) {
            if (Constants.FLAG_IS_SYSTEM_WEB) {
                // 使用系统默认的WebView
                ActivityUtils.switchActivityFinish(LoadingActivity.this, MainActivityV2.class);
            } else {
                // 使用腾讯x5内核的webView
                ActivityUtils.switchActivityFinish(LoadingActivity.this, MainActivity.class);
            }
        } else {
            Log.d(TAG, "jumpToHomePage: in");
            ActivityUtils.switchActivityFinish(LoadingActivity.this, LoginActivity.class);
        }
    }

    @Override
    public void initViews() {
        Log.d("H5", "LoadingActivity--initViews");
    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void onFinish() {
            Log.d(TAG, "jumpToHomePage: MyCountDownTimer");
            jumpToHomePage();
        }

        public void onTick(long millisUntilFinished) {
            String s = getResources().getString(R.string.s_jump);
            mCountDownTextView.setText(millisUntilFinished / 1000 + s);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        Log.d(TAG, "LoadingActivity--onDestroy");
    }

    private void findAllData() {
        List<TabItem> list = LitePal.findAll(TabItem.class);
        for (TabItem tabItem : list) {
            Log.d(TAG, tabItem.toString());
        }
    }

}
